package org.shj.thread.basic;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 *
 * @author Shen Huang Jian
 * @date 2018-01-02 16:30:27
 */
public class ForkJoinDemo extends RecursiveTask<Integer>{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final int THRESHOLD = 2;
	private int start;
	private int end;
	
	public ForkJoinDemo(int start, int end){
		this.start = start;
		this.end= end;
	}

	@Override
	protected Integer compute() {
		int sum = 0;
		boolean canCompute = (end - start) <= THRESHOLD; //如果任务足够小，就直接执行任务
		if(canCompute){
			System.out.println("Compute: " + start + " -- " + end);
			for( int i = start; i <= end; i++){
				sum += i;
			}
		}else{
			int middle = (start + end) /2;
			ForkJoinDemo leftTask = new ForkJoinDemo(start, middle);
			ForkJoinDemo rightTask = new ForkJoinDemo(middle + 1, end);
			
			//执行任务
			System.out.println("Compute: " + start + " -- " + middle);
			leftTask.fork(); //会调用子任务的 compute()方法
			System.out.println("Compute: " + (middle+1) + " -- " + end);
			rightTask.fork();
			
			//等待子任务执行完，并得到结果
			int leftResult = leftTask.join();
			System.out.println("Return: " + start + " -- " + middle);
			
			int rightResult = rightTask.join();
			System.out.println("Return: " + (middle+1) + " -- " + end);
			
			sum = leftResult + rightResult;//合并子任务结果
		}
		return sum;
	}
	
	public static void main(String[] args){
		ForkJoinPool forkJoinPool = new ForkJoinPool();
		ForkJoinDemo task = new ForkJoinDemo(1,100); //计算 1+2+3+...+99+100
		Future<Integer> result = forkJoinPool.submit(task);
		try{
			System.out.println(result.get());
		}catch(Exception e){
			
		}
		
	}
	
}
